import axios from 'axios'
import { useEffect, useState } from 'react'
export const day02_04 = function () {
    // const [list, setList] = useState([])
    // useEffect(() => {
    //     const getList = async () => {
    //         const res = await axios.get('http://localhost:3004/posts')
    //         setList(res.data)
    //     }
    //     getList()
    // }, [])

    const { list, setList } = useGetList()
    // 删除评论列表某一项
    const useDeleteListItem = function (id: string) {
        setList(list.filter((item: any) => item.id != id))
    }
    return (
        <>
            <h3>day02_04</h3>

            {list.map((item: any) => (
                <CommentListItem
                    key={item.id}
                    title={item.title}
                    views={item.views}
                    onDel={() => useDeleteListItem(item.id)}
                />
            ))}
        </>
    )
}

// 获取数据封装
const useGetList = function () {
    const [list, setList] = useState([])
    useEffect(() => {
        const getList = async () => {
            const res = await axios.get('http://localhost:3004/posts')
            setList(res.data)
        }
        getList()
    }, [])
    return { list, setList }
}

// 评论列表项组件封装
const CommentListItem = function (props: any) {
    return (
        <>
            <div>{props.title}</div>
            <div>{props.views}</div>
            <button onClick={props.onDel}>delete</button>
            <hr />
        </>
    )
}
